using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using RBAC.Domain.SmartHealthcare.Hosiptial;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using SmartHealthcare.Read.Api.Application.Command.Pharmacy;
using SmartHealthcare.Read.Api.DTo;

namespace SmartHealthcare.Read.Api.Application.Handler.Pharmacy
{
    /// <summary>
    /// 获取已发药处方列表处理器
    /// </summary>
    public class GetDispensedPrescriptionsHandler : IRequestHandler<GetDispensedPrescriptionsCommand, APIResult<List<PrescriptionDto>>>
    {
        private readonly IBaseRepository<Prescription> prescriptionRepository;
        private readonly IBaseRepository<PatientListModel> patientRepository;
        private readonly IBaseRepository<MedicineItem> medicineItemRepository;
        private readonly IMapper mapper;
        private readonly ILogger<GetDispensedPrescriptionsHandler> logger;

        public GetDispensedPrescriptionsHandler(
            IBaseRepository<Prescription> prescriptionRepository,
            IBaseRepository<PatientListModel> patientRepository,
            IBaseRepository<MedicineItem> medicineItemRepository,
            IMapper mapper,
            ILogger<GetDispensedPrescriptionsHandler> logger)
        {
            this.prescriptionRepository = prescriptionRepository;
            this.patientRepository = patientRepository;
            this.medicineItemRepository = medicineItemRepository;
            this.mapper = mapper;
            this.logger = logger;
        }

        public async Task<APIResult<List<PrescriptionDto>>> Handle(GetDispensedPrescriptionsCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<List<PrescriptionDto>>();

            try
            {
                // 查询已发药（状态为2）的处方，仅按时间范围过滤
                var query = prescriptionRepository.GetALL()
                    .Where(x => x.State == 2 && x.IsDeleted == false);

                // 按时间范围过滤
                if (request.DateRange.HasValue)
                {
                    DateTime start;
                    DateTime end = DateTime.Now.Date.AddDays(1);

                    switch (request.DateRange.Value)
                    {
                        case 0: // 今天
                            start = DateTime.Now.Date;
                            break;
                        case 1: // 本周
                            int delta = (int)DateTime.Now.DayOfWeek;
                            if (delta == 0) delta = 7;
                            start = DateTime.Now.Date.AddDays(-(delta - 1));
                            break;
                        case 2: // 本月
                            start = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
                            break;
                        case 3: // 今年
                            start = new DateTime(DateTime.Now.Year, 1, 1);
                            break;
                        case 4: // 全部
                            start = DateTime.MinValue;
                            end = DateTime.MaxValue;
                            break;
                        default:
                            start = DateTime.MinValue;
                            end = DateTime.MaxValue;
                            break;
                    }

                    if (start != DateTime.MinValue)
                    {
                        query = query.Where(x => x.CreateTime >= start && x.CreateTime < end);
                    }
                }

                var prescriptions = await query.OrderByDescending(x => x.CreateTime).ToListAsync(cancellationToken);

                var patientIds = prescriptions.Select(x => x.PatientName).Distinct().ToList();
                var patients = await patientRepository.GetALL()
                    .Where(x => patientIds.Contains(x.Id) && x.IsDeleted == false)
                    .ToListAsync(cancellationToken);

                var prescriptionIds = prescriptions.Select(x => x.Id).ToList();
                var medicineItems = await medicineItemRepository.GetALL()
                    .Where(x => prescriptionIds.Contains(x.PrescriptionId) && x.IsDeleted == false)
                    .ToListAsync(cancellationToken);

                var items = new List<PrescriptionDto>();
                foreach (var p in prescriptions)
                {
                    var patient = patients.FirstOrDefault(x => x.Id == p.PatientName);
                    var dto = mapper.Map<PrescriptionDto>(p);
                    if (patient != null)
                    {
                        dto.PatientName = patient.Name;
                        dto.PatientId = patient.Id;
                        dto.Gender = patient.Gender;
                        dto.MedicalCard = patient.MedicalCard;
                        dto.IdCard = patient.IdCard;
                    }
                    dto.StateDescription = "已发药"; // 状态2
                    dto.MedicineItems = mapper.Map<List<MedicineItemDto>>(medicineItems.Where(x => x.PrescriptionId == p.Id));
                    items.Add(dto);
                }

                result.Data = items;
                result.Code = APIEnums.Success;
                result.Msg = "查询成功";

                logger.LogInformation($"查询已发药处方成功，共找到 {items.Count} 条记录");
            }
            catch (Exception ex)
            {
                result.Code = APIEnums.Error;
                result.Msg = "查询失败：" + ex.Message;
                logger.LogError(ex, "查询已发药处方失败");
            }

            return result;
        }
    }
}


